function evaluateLinks()
{
	var generatedLinks = [];
	var correctLinks = [];

	var reverse = $('#reverse').attr('checked');

	var lines = $('#correct_links').val().split('\n');
	for (var i in lines) {
		if (lines[i].match(/<(.+)>\s+(.+)\s+<(.+)>/)) {
			correctLinks.push({
				'src': reverse ? RegExp.$3 : RegExp.$1,
				'type': RegExp.$2,
				'dst': reverse ? RegExp.$1 : RegExp.$3
			});
		}
	}

	lines = $('#generated_links').val().split('\n');
	for (var i in lines) {
		if (lines[i].match(/<(.+)>\s+(.+)\s+<(.+)>/)) {
			generatedLinks.push({
				'src': RegExp.$1,
				'type': RegExp.$2,
				'dst': RegExp.$3
			});
		}
	}

	compareLinks(generatedLinks, correctLinks);
}

function linkInArray(link, links)
{
	for (var i in links) {
		if (links[i].src == link.src && links[i].dst == link.dst && links[i].type == link.type) {
			return true;
		}
	}

	return false;
}

function compareLinks(generatedLinks, correctLinks)
{
	var numRecalled = 0
	var incorrectLinks = [];

	for (var i in generatedLinks) {
		var isCorrect = false;
		if (linkInArray(generatedLinks[i], correctLinks)) {
			numRecalled++;
		} else {
			incorrectLinks.push(generatedLinks[i]);
		}
	}

	var precision = numRecalled / generatedLinks.length;
	var recall = numRecalled / correctLinks.length;

	var f1 = 2 * (precision * recall) / (precision + recall);

	var missingLinks = [];
	for (var i in correctLinks) {
		if (!linkInArray(correctLinks[i], generatedLinks)) {
			missingLinks.push(correctLinks[i]);
		}
	}

	$('#precision').text(precision);
	$('#recall').text(recall);
	$('#f1_measure').text(f1);

	var missingField = '';
	for (var i in missingLinks) {
		var l = missingLinks[i];
		missingField += '<' + l.src  + '> ' + l.type + ' <' + l.dst  + '>\n';
	}
	$('#missing_links').val(missingField);

	var incorrectField = '';
	for (var i in incorrectLinks) {
		var l = incorrectLinks[i];
		incorrectField += '<' + l.src  + '> ' + l.type + ' <' + l.dst  + '>\n';
	}
	$('#incorrect_links').val(incorrectField);

	$('#num_missing').text(missingLinks.length + ' of ' + correctLinks.length);
	$('#num_incorrect').text(incorrectLinks.length + ' of ' + generatedLinks.length);
}

function init()
{
	$('#evaluate_btn').click(evaluateLinks);
	$('#clear_correct').click(function() { $('#correct_links').val(''); });
	$('#clear_generated').click(function() { $('#generated_links').val(''); });
}

$(init);
